//
//  ReadPagePopView.m
//  KidReading
//
//  Created by telen on 16/1/20.
//  Copyright © 2016年 刘赞黄Telen. All rights reserved.
//

#import "ReadPagePopView.h"
#import "ConstDefine.h"

static NSMutableArray* readPagePopView_marr = nil;

@implementation PageImageScrollView
{
    UITapGestureRecognizer* tap;
}
- (void)setTapForNext:(BOOL)tapForNext
{
    _tapForNext = tapForNext;
    if (!tap && tapForNext) {
        tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(taped)];
        [self addGestureRecognizer:tap];
        tap.rippleColor = __BaseBackColor;
        [tap addTapRipple];
    }
    if (tap && !tapForNext) {
        [self removeGestureRecognizer:tap],tap = nil;
    }
}
- (void)taped
{
    if (self.scrollEnabled && _tapForNext) {
        CGPoint offset = self.contentOffset;
        long w = self.frame.size.width;
        long x = (long)offset.x + w/2;
        long index = x/w+1;
        CGRect frame = self.frame;
        frame.origin.x = index*w;
        if (frame.origin.x + 1 > self.contentSize.width) {
            frame.origin.x = 0;
        }
        [self scrollRectToVisible:frame animated:YES];
    }
}
//-------
- (void)addPanForScrollView
{
    [self.panGestureRecognizer addTarget:self action:@selector(didDragged:)];
}

- (void)didDragged:(UIPanGestureRecognizer*)sender
{
    if (sender.state == UIGestureRecognizerStateChanged) {
        //注意，这里取得的参照坐标系是该对象的上层View的坐标。
        CGPoint offset = [sender translationInView:self];
        if ((self.contentOffset.x < 0.001 && offset.x > 1)
            || (self.contentOffset.x + 0.001 > self.contentSize.width - self.frame.size.width && offset.x < -1))
        {
            self.scrollEnabled = NO;
            [self performSelector:@selector(_delayEnable) withObject:nil afterDelay:0.5];
        }
    }
}
- (void)_delayEnable
{
    self.scrollEnabled = YES;
}
@end

#pragma mark-
@interface PageAudioSlider : UISlider
@property(nonatomic,strong)void(^block_clickChangedValue)(void);
@end
@implementation PageAudioSlider
{
    float clickTemp;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    CGRect t = [self trackRectForBounds: [self bounds]];
    float v = [self minimumValue] + ([[touches anyObject] locationInView: self].x - t.origin.x - 4.0) * (([self maximumValue]-[self minimumValue]) / (t.size.width - 8.0));
    clickTemp = v;
    [super touchesBegan: touches withEvent: event];
}
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGRect t = [self trackRectForBounds: [self bounds]];
    float v = [self minimumValue] + ([[touches anyObject] locationInView: self].x - t.origin.x - 4.0) * (([self maximumValue]-[self minimumValue]) / (t.size.width - 8.0));
    if (clickTemp == v) {
        self.value = v,clickTemp = 0;
        if (_block_clickChangedValue)_block_clickChangedValue();
    }
    [super touchesEnded: touches withEvent: event];
}
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    CGRect t = [self trackRectForBounds: [self bounds]];
    float v = [self minimumValue] + ([[touches anyObject] locationInView: self].x - t.origin.x - 4.0) * (([self maximumValue]-[self minimumValue]) / (t.size.width - 8.0));
    if (clickTemp == v) {
        self.value = v,clickTemp = 0;
        if (_block_clickChangedValue)_block_clickChangedValue();
    }
    [super touchesCancelled: touches withEvent: event];
}
@end

#pragma mark-
#define PodAudioCtr 10
@implementation PageAudioCtrView
{
    StatusButton_2_View* pauseBtn;
    UILabel* leftLabel;
    UILabel* rightLabel;
    PageAudioSlider* slider;
    AVAudioPlayer* audioPlayer;
    //
    NSTimer* timer;
}
+ (instancetype)getAudioCtr
{
    return [[PageAudioCtrView alloc] init];
}

- (void)updatePauseBtnStatus
{
    if (pauseBtn == nil) {
        CGRect frame = self.bounds;
        frame.size = CGSizeMake(30/self.ratio, 30/self.ratio);
        frame.origin.x = PodAudioCtr/self.ratio;
        frame.origin.y = (self.bounds.size.height - frame.size.height)*0.5;
        pauseBtn = [[StatusButton_2_View alloc] initWithFrame:frame imageOn:@"page_btn_videosuspend.png" imageOff:@"page_btn_videobegin.png"];
        [self addSubview:pauseBtn];
        __weak AVAudioPlayer* waudioPlayer = audioPlayer;
        __weak StatusButton_2_View* wpauseBtn = pauseBtn;
        __weak NSTimer* wtimer = timer;
        __weak Blok_toPlay btplay = _blocktoplay;
        pauseBtn.btnClicked = ^(StatusButtonView* sBtn){
            if(!wpauseBtn.onOff){
                [waudioPlayer pause];
                wtimer.fireDate = [NSDate distantFuture];
                if(btplay)btplay(NO);
            }else{
                [waudioPlayer play];
                wtimer.fireDate = [NSDate distantPast];
                if(btplay)btplay(YES);
            }
        };
    }
    if (audioPlayer.isPlaying) {
        [pauseBtn setButtonStatus:YES];
    }
    //debug
//    pauseBtn.layer.borderColor = [UIColor redColor].CGColor;
//    pauseBtn.layer.borderWidth = 1;
}

- (void)updateLeftLabel
{
    if (leftLabel == nil) {
        CGRect frame = self.bounds;
        frame.size = CGSizeMake(100/self.ratio, 60/self.ratio);
        frame.origin.x = pauseBtn.origin.x+pauseBtn.size.width;
        frame.origin.y = (self.bounds.size.height - frame.size.height)*0.5;
        leftLabel = [[UILabel alloc] initWithFrame:frame];
        leftLabel.backgroundColor = [UIColor clearColor];
        leftLabel.font = [UIFont systemFontOfSize:frame.size.height*0.48];
        leftLabel.textColor = [UIColor whiteColor];
        leftLabel.textAlignment = NSTextAlignmentCenter;
        leftLabel.shadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        leftLabel.shadowOffset = CGSizeMake(1, 1);
        leftLabel.layer.anchorPoint = CGPointMake(1, 0.5);
        leftLabel.transform = CGAffineTransformMakeScale(0.5, 0.5);
        [self addSubview:leftLabel];
    }
    NSTimeInterval time = audioPlayer.currentTime;
    leftLabel.text = [self stringWithformatWithUTCTime:@"mm:ss" Date:[NSDate dateWithTimeIntervalSince1970:time]];
//    leftLabel.text = [[NSDate dateWithTimeIntervalSince1970:time] stringWithFormat:@"mm:ss"];
    //debug
//    leftLabel.layer.borderColor = [UIColor redColor].CGColor;
//    leftLabel.layer.borderWidth = 1;
}

- (void)updateRightLabel
{
    if (rightLabel == nil) {
        CGRect frame = self.bounds;
        frame.size = CGSizeMake(100/self.ratio, 60/self.ratio);
        frame.origin.x = self.bounds.size.width - frame.size.width -  PodAudioCtr/self.ratio;
        frame.origin.y = (self.bounds.size.height - frame.size.height)*0.5;
        rightLabel = [[UILabel alloc] initWithFrame:frame];
        rightLabel.backgroundColor = [UIColor clearColor];
        rightLabel.font = [UIFont systemFontOfSize:frame.size.height*0.48];
        rightLabel.textColor = [UIColor whiteColor];
        rightLabel.textAlignment = NSTextAlignmentCenter;
        rightLabel.shadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.2];
        rightLabel.shadowOffset = CGSizeMake(1, 1);
        rightLabel.layer.anchorPoint = CGPointMake(0, 0.5);
        rightLabel.transform = CGAffineTransformMakeScale(0.5, 0.5);
        [self addSubview:rightLabel];
    }
    NSTimeInterval time = audioPlayer.duration;
    rightLabel.text = [self stringWithformatWithUTCTime:@"mm:ss" Date:[NSDate dateWithTimeIntervalSince1970:time]];
//    rightLabel.text = [[NSDate dateWithTimeIntervalSince1970:time] stringWithFormat:@"mm:ss"];
    //debug
//    rightLabel.layer.borderColor = [UIColor redColor].CGColor;
//    rightLabel.layer.borderWidth = 1;
}

//
- (NSString *)stringWithformatWithUTCTime:(NSString *)format Date:(NSDate*)date{
    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
    return [formatter stringFromDate:date];
}

- (void)doneSetting
{
    if (!CGRectEqualToRect(self.frame, CGRectZero)) {
        //
        audioPlayer = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:self.mp3file];
        //NSTimeInterval duration = audioPlayer.duration;
        timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(tick) userInfo:nil repeats:YES];
        timer.fireDate = [NSDate distantPast];
        //
        self.backgroundColor = [UIColor clearColor];
        UIView* bg = [[UIView alloc] initWithFrame:self.bounds];
        [self addSubview:bg];
        if ([@"normal" isEqualToString:self.audio_style]) {
            bg.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        }else{
            [bg.layer setCornerRadius:self.frame.size.height*0.5];
            [bg.layer setMasksToBounds:YES];
            bg.backgroundColor = [[UIColor colorWithHexString:@"#b8b8b8"] colorWithAlphaComponent:0.99];
        }
        //
        [self updatePauseBtnStatus];
        [self updateLeftLabel];
        [self updateRightLabel];
        
        CGRect frame = self.bounds;
        frame.origin.x = leftLabel.origin.x+leftLabel.size.width;
        frame.size.width = rightLabel.origin.x - frame.origin.x;
        
        if (frame.size.width <= 0) {
            NSLog(@"Error Rect For AudioCtr");
        }else{
            //Slider
            slider = [[PageAudioSlider alloc] initWithFrame:frame];
            [self addSubview:slider];
            slider.minimumValue = 0;
            slider.maximumValue = 1;
            slider.continuous = NO;
            slider.minimumTrackTintColor = [UIColor whiteColor];
            slider.maximumTrackTintColor = [[UIColor whiteColor] colorWithAlphaComponent:0.2];
            [slider addTarget:self action:@selector(changedSlider) forControlEvents:UIControlEventValueChanged];
            __weak PageAudioCtrView* wSelf = self;
            slider.block_clickChangedValue = ^{
                [wSelf changedSlider];
            };
        }
        [self addTapGesture_Undo];
    }
}
                 
- (void)tick
{
    if(slider.state == UIControlStateNormal)slider.value = audioPlayer.currentTime*1.0/audioPlayer.duration;
    [self updateLeftLabel];
    [self updateRightLabel];
}

- (void)changedSlider
{
    NSTimeInterval toTime = slider.value*audioPlayer.duration;
    audioPlayer.currentTime = toTime < audioPlayer.duration-0.5 ? toTime : audioPlayer.duration-0.5;
    [self updateLeftLabel];
    //NSLog(@"%@[%@]%@ %@",@(slider.minimumValue),@(slider.value),@(slider.maximumValue),@(audioPlayer.duration));
}

- (void)dealloc
{
    [timer invalidate],timer = nil;
}

@end

#pragma mark-
@interface ReadPagePopView()<TLSoundPlayerDelegate>
@end
@implementation ReadPagePopView
{
    StatusButton_2_View* readPlayBtn;
    PageAudioCtrView* pageAudioCtr;
    NSString* mp3File;
    NSString* mp3File_unCode;
    
    //
    UIWebView *_webView;
    UIButton *_xBtn;
}

@synthesize pageView,rectview,popInfo;

- (instancetype)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
//        self.layer.borderColor = [UIColor redColor].CGColor;
//        self.layer.borderWidth = 1.0;
    }
    return self;
}

- (void)statusBarOrientationChange {
//    UIInterfaceOrientation orienta = [[UIApplication sharedApplication] statusBarOrientation];
//    NSLog(@"--orienta--%ld",(long)orienta);
    if (self) {
        CGRect originRect = self.frame;
        [self JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
            make.left.JRMAS_equalTo(originRect.origin.y);
            make.top.JRMAS_equalTo(originRect.origin.x);
            make.size.JRMAS_equalTo(CGSizeMake(originRect.size.height, originRect.size.width));
        }];
    }
}

- (void)addHostArea_adv_Img_Sign:(UIScrollView*)scrollview
{
    //处理图片滚动示意标签
    if (scrollview && scrollview.superview) {
        CGFloat sw = scrollview.frame.size.width;
        CGFloat sh = scrollview.frame.size.height;
        CGFloat iw = scrollview.contentSize.width;
        CGFloat ih = scrollview.contentSize.height;
        if (sw <=0 || sh <=0) {
            NSLog(@"Error: scroll<%@ %@>  img<%@ %@>",@(sw),@(sh),@(iw),@(ih));
            return;
        }
        CGPoint ct = self.center;
        CGFloat pod = 16;
        CGRect frame = self.bounds;
        if (sw < iw  && sh < ih) {
            UIImage* image = [UIImage imageNamed:@"page_icon_picture3.png"];
            frame.size = CGSizeMake(image.size.width*0.5, image.size.height*0.5);
            frame.origin = CGPointMake(pod, pod);
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            imgv.image = image;
            [self addSubview:imgv];
        }else if(sh < ih){
            UIImage* image = [UIImage imageNamed:@"page_icon_picture1.png"];
            frame.origin.y += pod*4;
            frame.size = CGSizeMake(image.size.width*0.5, image.size.height*0.5);
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            imgv.image = image;
            [self addSubview:imgv];
            CGPoint ptc = imgv.center;
            if (ct.x <= pageView.contentView_Scale.center.x) {
                ptc.x =  self.bounds.size.width-pod*2;
            }else{
                ptc.x += pod;
            }
            imgv.center = ptc;
            
        }else if(sw < iw){
            UIImage* image = [UIImage imageNamed:@"page_icon_picture2.png"];
            frame.origin.y += frame.size.height-pod;
            frame.origin.x += frame.size.width-pod;
            frame.size = CGSizeMake(image.size.width*0.5, image.size.height*0.5);
            frame.origin.y += -frame.size.height;
            frame.origin.x += -frame.size.width;
            UIImageView* imgv = [[UIImageView alloc] initWithFrame:frame];
            imgv.image = image;
            [self addSubview:imgv];
            if([scrollview isKindOfClass:[PageImageScrollView class]])[(PageImageScrollView*)scrollview addPanForScrollView];
        }
    }
}

- (BOOL)isRectViewPoped:(UIView*)view
{
    if (!readPagePopView_marr) {
        readPagePopView_marr = [NSMutableArray new];
        return NO;
    }
    if(view)for (NSValue* value in readPagePopView_marr) {
        if (value.nonretainedObjectValue == view) {
            return YES;
        }
    }
    return NO;
}

- (void)addRectViewPop:(UIView*)view
{
    if (!readPagePopView_marr) {
        readPagePopView_marr = [NSMutableArray new];
    }
    if([view isKindOfClass:[KoK_RectView class]])[readPagePopView_marr addObject:[NSValue valueWithNonretainedObject:view]];
}

- (void)removeRectViewPop:(UIView*)view
{
    if (view && readPagePopView_marr) {
        for (NSValue* value in readPagePopView_marr) {
            if (value.nonretainedObjectValue == view) {
                [readPagePopView_marr removeObject:value];
                return;
            }
        }
    }
}

- (CGRect)getRect:(NSString*)str
{
    NSArray* rect = [DataProcessing getNumbersFromString:str];
    if (rect.count != 4) {
        rect = @[@(0),@(0),@(0),@(0)];
    }
    CGFloat w = [rect[2] floatValue] -[rect[0] floatValue];
    CGFloat h = [rect[3] floatValue] -[rect[1] floatValue];
    CGFloat x = [rect[0] floatValue];
    CGFloat y = [rect[1] floatValue];
    w *= self.bookRatioWH;
    h *= self.bookRatioWH;
    x *= self.bookRatioWH;
    y *= self.bookRatioWH;
    return CGRectMake(floor(x), floor(y), ceil(w), ceil(h));
}

- (CGRect)keepInPageRect:(CGRect)rect
{
    UIView* view = pageView.contentView_Scale;
    CGRect vrect = view.bounds;
    if (!CGRectContainsRect(vrect, rect)) {
        //x+
        CGFloat distane = 0;
        distane = (rect.origin.x + rect.size.width) - (vrect.origin.x+ vrect.size.width);
        if (distane > 0) {
            rect.origin.x -= distane;
        }
        //y+
        distane = (rect.origin.y + rect.size.height) - (vrect.origin.y+ vrect.size.height);
        if (distane > 0) {
            rect.origin.y -= distane;
        }
        //x-
        distane = rect.origin.x - vrect.origin.x;
        if (distane < 0) {
            rect.origin.x -= distane;
        }
        //y-
        distane = rect.origin.y - vrect.origin.y;
        if (distane < 0) {
            rect.origin.y -= distane;
        }
    }
    return rect;
}

- (StatusButton_2_View*)getPlayBtn_audioStyle:(NSString*)audio_style rect:(CGRect)rectlb
{
    StatusButton_2_View* readPlayBtn_ = [[StatusButton_2_View alloc] initWithFrame:rectlb imageOn:nil imageOff:@"page_btn_suona1.png"];
    NSArray* arrAni = [NSArray arrayWithObjects:[UIImage imageNamed:@"page_btn_suona1.png"],[UIImage imageNamed:@"page_btn_suona2.png"],[UIImage imageNamed:@"page_btn_suona3.png"], nil];
    [readPlayBtn_ setAni_UImageArr:arrAni ani_duration:1 forStatus:YES];
    return readPlayBtn_;
}

- (void)show:(UIViewController *)parentVC
{
    if (pageView && rectview && popInfo && ![self isRectViewPoped:rectview]) {
        NSDictionary* pop = popInfo;
        NSString* status = pop[@"status"];
        nullToNil(status);
        BOOL status_valid = [status isEqualToString:@"valid"];
        if (status_valid) {
            NSString* ecodetype = pop[@"encode_type"];
            nullToNil(ecodetype);
            BOOL needDecode = [ecodetype isEqualToString:@"normal"];
            NSString* mode = pop[@"mode"];
            nullToNil(mode);
            BOOL mode1_1 = [mode isEqualToString:@"1:1"];
            NSArray* source = pop[@"source"];
            nullToNil(source);
            //
            CGRect rect = [self getRect:[pop objectForKey:@"rect"]];
            CGFloat w = rect.size.width;
            CGFloat h = rect.size.height;
            CGFloat x = rect.origin.x;
            CGFloat y = rect.origin.y;
            
            //自取第一个弹出
            if (source && source.count > 0) {
                if (source.count >1) {
                    NSLog(@"Error popup %@",@(source.count));
                }
                //
                NSDictionary* dic = source.firstObject;
                NSString* htype = dic[@"type"];
                nullToNil(htype);
                NSArray* uris = dic[@"uri"];
                nullToNil(uris);
                NSString* uri = uris.firstObject;
                if (![uri isKindOfClass:[NSString class]]) {
                    uri = nil;
                    NSLog(@"Error uri is Not NSString");
                }
                NSDictionary* bg = dic[@"bg"];
                nullToNil(bg);
                NSString* statusbg = bg[@"status"];
                nullToNil(statusbg);
                BOOL statusbg_valid = [statusbg isEqualToString:@"valid"];
                //
                CGRect rectbg = [self getRect:[bg objectForKey:@"rect"]];
                CGFloat wbg = rectbg.size.width;
                CGFloat hbg = rectbg.size.height;
                CGFloat xbg = rectbg.origin.x;
                CGFloat ybg = rectbg.origin.y;
                
                //按照热区创建贴图
                
                self.backgroundColor = [UIColor clearColor];
                UIView *parentView = nil;
                if (parentVC) {
                    //self.frame = parentVC.view.bounds;
                    //[parentVC.view addSubview:self];
                    parentView = parentVC.view;
                    [parentView addSubview:self];
                }else{
                    [pageView.contentView_Scale addSubview:self];
                }
                
                [self JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                    make.size.JRMAS_equalTo(CGSizeMake(w, h));
                    make.left.JRMAS_equalTo(x);
                    make.top.JRMAS_equalTo(y);
                }];
                [self layoutIfNeeded];
                __weak ReadPagePopView *wself = self;
                
                //self.frame = CGRectMake(x, y, w, h);
                
                //背景处理
                if (statusbg_valid) {
                    [self JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
                        make.size.JRMAS_equalTo(CGSizeMake(wbg, hbg));
                        make.left.JRMAS_equalTo(xbg);
                        make.top.JRMAS_equalTo(ybg);
                    }];
                    //self.frame = CGRectMake(xbg, ybg, wbg, hbg);
                }
                
                
                BOOL smallBtn = NO;
                BOOL hasXbtn = YES;
                //
                if([htype isEqualToString:@"img"] && uri){
                    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                    //NSString* fileTo = [file stringByAppendingString:@".png"];
                    NSData* imageData = nil;
                    if (needDecode) {
                        //BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
                        //if(ret){
                        //    imageData = [[NSData alloc] initWithContentsOfFile:fileTo];
                        //}
                        //[[NSFileManager defaultManager] removeItemAtPath:fileTo error:nil];
                        imageData = [[NSData alloc] initWithContentsOfFile:file];
                        imageData = [WYCryptDES decryptFileData:imageData key:__WYDEC_Code];
                    }else{
                        imageData = [[NSData alloc] initWithContentsOfFile:file];
                    }
                    
                    //MARK:图片处理
                    if (imageData) {
                        UIImage* image = [[UIImage alloc] initWithData:imageData scale:2.0];
                        
                        //1:1模式
                        if (mode1_1) {
                            UIImageView* igv = [[UIImageView alloc] initWithImage:image];
                            CGRect frame = igv.frame;
                            frame.size.width = floor(frame.size.width / _ratio);
                            frame.size.height = floor(frame.size.height / _ratio);
                            igv.frame = frame;
                            igv.userInteractionEnabled = YES;
                            CGRect rect = CGRectMake(0, 0, w, h);
                            PageImageScrollView* scrollview = [[PageImageScrollView alloc] initWithFrame:rect];
                            scrollview.showsHorizontalScrollIndicator = NO;
                            scrollview.showsVerticalScrollIndicator = NO;
                            scrollview.bounces = NO;
                            scrollview.contentSize = frame.size;
                            [scrollview addSubview:igv];
                            [self addSubview:scrollview];
                            
                            //处理图片滚动示意标签
                            [self addHostArea_adv_Img_Sign:scrollview];
                            
                            if (!(frame.size.width <= w && frame.size.height <= h)) {
                                smallBtn = YES;
                            }
                            
                            //
                            //debug
                            //scrollview.layer.borderWidth = 1;
                            //scrollview.layer.borderColor = [[UIColor yellowColor] colorWithAlphaComponent:0.6].CGColor;
                        }
                    }
                }
                
                
                //MARK:Html5
                else if ([htype isEqualToString:@"h5"]) {
                    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                    NSString* fileTo = [file stringByAppendingString:@".html"];
                    NSData* h5Data = nil;
                    if (needDecode) {
                        //BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
                        //if(ret){
                        //    h5Data = [[NSData alloc] initWithContentsOfFile:fileTo];
                        //}
                        //[[NSFileManager defaultManager] removeItemAtPath:fileTo error:nil];
                        h5Data = [[NSData alloc] initWithContentsOfFile:file];
                        h5Data = [WYCryptDES decryptFileData:h5Data key:__WYDEC_Code];
                    }else{
                        h5Data = [[NSData alloc] initWithContentsOfFile:file];
                    }
                    
                    if (h5Data) {
                        CGRect rect = self.bounds;
                        UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
                        webView.mediaPlaybackRequiresUserAction = NO;
                        webView.allowsInlineMediaPlayback = YES;
                        if (parentView) {
                            [parentView addSubview:webView];
                            [webView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                                make.edges.equalTo(parentView);
                            }];
                        }else {
                            [self addSubview:webView];
                            [webView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                                make.edges.equalTo(wself);
                            }];
                        }
                        _webView = webView;
                        webView.delegate = self;
                        webView.scrollView.contentSize = rect.size;
                        webView.scrollView.showsHorizontalScrollIndicator = NO;
                        webView.scrollView.showsVerticalScrollIndicator = NO;
                        webView.opaque = NO;
                        webView.backgroundColor = [UIColor clearColor];
                        NSString* fileBase = [fileTo stringByDeletingLastPathComponent];
                        [webView loadData:h5Data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL fileURLWithPath:fileBase]];
                        //Pep统计 H5开始
                        ReadBookVOrH_VC* rvc = [ReadBookVOrH_VC currentReadInstance];
                        NSString *pageStr = self.pageView.pageId;
                        NSArray *sourceArr = [pop valueForKey:@"source"];
                        NSDictionary *sourceDcit =sourceArr[0];
                        NSArray *uriArr = [sourceDcit valueForKey:@"uri"];
                        NSString *uriStr = [uriArr[0] lastPathComponent];
                        NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                        NSString *srcId = rectview.src_id;
                        if (pageStr && uriStr && type) {
                            NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"H5",@"op",@(self.bookid).description,@"bid", pageStr,@"pg",@(1).description,@"opc" ,uriStr,@"fnm" ,type,@"ext",nil];
                            if (srcId) {
                                [opDict setValue:srcId forKey:@"resid"];
                            }
                            [NSObject msgToTarget:rvc menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(YES)] needReturnValue:NO];
                        }
                        
                        //debug
                        //webView.layer.borderWidth = 1;
                        //webView.layer.borderColor = [[UIColor yellowColor] colorWithAlphaComponent:0.6].CGColor;
                        //
                        smallBtn = YES;
                    }
                }
                
                
                //MARK:弹出音频播放样式
                else if ([htype isEqualToString:@"audio"] && uri){
                    //Pep统计：音频播放开始
                    ReadBookVOrH_VC* rvc = [ReadBookVOrH_VC currentReadInstance];
                    NSString *pageStr = self.pageView.pageId;
                    NSArray *sourceArr = [pop valueForKey:@"source"];
                    NSDictionary *sourceDcit =sourceArr[0];
                    NSArray *uriArr = [sourceDcit valueForKey:@"uri"];
                    NSString *uriStr = [uriArr[0] lastPathComponent];
                    NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                    NSString *srcId = rectview.src_id;
                    if (pageStr && uriStr && type) {
                        NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"sound",@"op",@(self.bookid).description,@"bid", pageStr,@"pg",@(1).description,@"opc" ,uriStr,@"fnm" ,type,@"ext",nil];
                        if (srcId) {
                            [opDict setValue:srcId forKey:@"resid"];
                        }
                        [NSObject msgToTarget:rvc menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(YES)] needReturnValue:NO];
                    }
                    //
                    self.frame = CGRectZero;
                    hasXbtn = NO;
                    //
                    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:uri];
                    NSString* fileTo = [file stringByAppendingString:@".mp3"];
                    mp3File = file;
                    if (needDecode) {
                        BOOL ret = [WYCryptDES decryptFile:file toFile:fileTo withKey:__WYDEC_Code];
                        if(ret){
                            mp3File = fileTo;
                            mp3File_unCode = fileTo;
                        }
                    }
                    //
                    if (rectview.mutex == 1) {
                        // 互斥 数据配置要求的互斥
                        [[TLSoundPlayer shareSingle] stopAllFiles];
                        [self.pageView update_KOK_toPlayMSecond:0 andSentenceIndex:0];
                    }
                    //
                    [[TLSoundPlayer shareSingle] stopFilePlay_andClean:mp3File];
                    BOOL playOK = [[TLSoundPlayer shareSingle] prepareToPlayFile:mp3File andDelegate:self];
                    if (!playOK) {
                        if (!playOK) {
                            mp3File = nil;
                            [self _x];
                            return;
                        }
                    }else{
                        AVAudioPlayer* player = [[TLSoundPlayer shareSingle] getAudioPlayerForPlayFile:mp3File];
                        [player setCurrentTime:ULONG_MAX];
                        if([player play])[readPlayBtn setButtonStatus:YES];
                        [player setCurrentTime:0];
                    }
                    //
                    NSString* pgrrect = dic[@"audio_rect_progress"];
                    NSString* lbrect = dic[@"audio_rect_laba"];
                    NSString* audio_style = dic[@"audio_style"];
                    nullToNil(pgrrect);
                    nullToNil(lbrect);
                    nullToNil(audio_style);
                    //样式处理
                    if (lbrect && lbrect.length > 0) {
                        CGRect rectlb = [self getRect:lbrect];
                        readPlayBtn = [self getPlayBtn_audioStyle:audio_style rect:rectlb];
                        [readPlayBtn setButtonStatus:YES];
                        __weak ReadPagePopView *weakself = self;
                        readPlayBtn.btnClicked = ^(StatusButtonView* sBtn){
                            [wself _x];
                            //Pep统计：声音播放结束
                            ReadBookVOrH_VC* rvc = [ReadBookVOrH_VC currentReadInstance];
                            NSString *pageStr = weakself.pageView.pageId;
                            NSArray *sourceArr = [pop valueForKey:@"source"];
                            NSDictionary *sourceDcit =sourceArr[0];
                            NSArray *uriArr = [sourceDcit valueForKey:@"uri"];
                            NSString *uriStr = [uriArr[0] lastPathComponent];
                            NSString *type = [[uriStr componentsSeparatedByString:@"."] lastObject];
                            if (pageStr && uriStr && type) {
                                NSMutableDictionary *opDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"sound",@"op",@(weakself.bookid).description,@"bid", pageStr,@"pg",@(1).description,@"opc" ,uriStr,@"fnm" ,type,@"ext",nil];
                                if (srcId) {
                                    [opDict setValue:srcId forKey:@"resid"];
                                }
                                [NSObject msgToTarget:rvc menthed:@"pepSatisticSrouce_read:isBegin:" refs:@[opDict,@(NO)] needReturnValue:NO];
                            }
                        };
                        [pageView.contentView_Scale addSubview:readPlayBtn];
                        //debug
                        //readPlayBtn.layer.borderWidth = 1;
                        //readPlayBtn.layer.borderColor = [[UIColor yellowColor] colorWithAlphaComponent:0.6].CGColor;
                        //
                    }
                    __weak StatusButton_2_View* wreadPlayBtn = readPlayBtn;
                    if (pgrrect && pgrrect.length > 0) {
                        CGRect rectpgr = [self getRect:pgrrect];
                        rectpgr = [self keepInPageRect:rectpgr];
                        pageAudioCtr = [PageAudioCtrView getAudioCtr];
                        pageAudioCtr.frame = rectpgr;
                        [pageView.contentView_Scale addSubview:pageAudioCtr];
                        pageAudioCtr.audio_style = audio_style;
                        pageAudioCtr.ratio = self.ratio;
                        pageAudioCtr.mp3file = mp3File;
                        pageAudioCtr.blocktoplay = ^(BOOL play){
                            if(wreadPlayBtn)[wreadPlayBtn setButtonStatus:play];
                        };
                        [pageAudioCtr doneSetting];
                        __weak ReadPagePopView* _wself = self;
                        [pageAudioCtr addPanGesture_Move_End:^(UIView *view, CGPoint offset) {
                            view.frame = [_wself keepInPageRect:view.frame];
                        }];
                        //debug
                        //pageAudioCtr.layer.borderWidth = 1;
                        //pageAudioCtr.layer.borderColor = [[UIColor yellowColor] colorWithAlphaComponent:0.6].CGColor;
                        //
                    }
                }
                
                //按钮
                UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
                //btn.frame = self.bounds;
                if(hasXbtn){
                    if (parentView) {
                        [parentView addSubview:btn];
                    }else {
                        [self addSubview:btn];
                    }
                    [btn JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
                        make.size.JRMAS_equalTo(CGSizeMake(wself.bounds.size.width, wself.bounds.size.height));
                        make.center.equalTo(wself);
                        //make.top.right.equalTo(parentView);
                    }];
                }
                btn.exclusiveTouch = YES;
                _xBtn = btn;
                [btn addTarget:self action:@selector(_x) forControlEvents:UIControlEventTouchUpInside];
                
                //背景处理
                if (statusbg_valid) {
                    NSString* file =  [DataProcessing bookPathForBookID:self.bookid subDir:bg[@"source"]];
                    UIImage* image = [[UIImage alloc] initWithContentsOfFile:file];
                    UIImageView* igv = [[UIImageView alloc] initWithFrame:self.bounds];
                    igv.image = image;
                    [self addSubview:igv];
                    [self sendSubviewToBack:igv];
                    smallBtn = YES;
                }
                
                //Btn样式处理
                if (smallBtn && hasXbtn) {
                    CGFloat pod = 16;
                    UIImage* image = [UIImage imageNamed:@"page_btn_cloes_normal.png"];
                    [btn setImage:image forState:UIControlStateNormal];
                    //CGRect frame = CGRectMake(0, pod, image.size.width*0.5, image.size.height*0.5);
                    //btn.frame = frame;
                    CGPoint ct = self.center;
                    CGPoint ptc = btn.center;
                    CGFloat rightoff = ptc.x;
                    if (ct.x <= pageView.contentView_Scale.center.x || ct.x <= parentVC.view.center.x) {
                        ptc.x =  self.bounds.size.width-pod*2;
                        rightoff = pod*2;
                    }else{
                        ptc.x += pod;
                        rightoff = ptc.x;
                    }
                    //btn.center = ptc;
                    UIView *layoutV = parentView;
                    if (!parentView) {
                        layoutV = self;
                    }
                    [btn JRMAS_remakeConstraints:^(JRMASConstraintMaker *make) {
                        make.size.JRMAS_equalTo(CGSizeMake(image.size.width*0.5, image.size.height*0.5));
                        //make.center.JRMAS_equalTo(ptc);
                        make.top.equalTo(layoutV.JRMAS_top).offset(pod);
                        make.right.equalTo(layoutV.JRMAS_right).offset(-rightoff);
                    }];
                    [btn addTouchScaleTransitions];
                    btn.rippleColor = __BaseBackColor;
                    [btn addTouchUpInside_Ripple];
                }
                
                [self addRectViewPop:rectview];
                [self playShow];
                
                //debug
                //self.layer.borderWidth = 1;
                //self.layer.borderColor = [[UIColor redColor] colorWithAlphaComponent:0.6].CGColor;
                
            }
        }
    }
}

- (void)playShow
{
    if (rectview.helperIcon.hidden) {
        return;
    }
    self.alpha = 0.001f;
    readPlayBtn.alpha = 0.0001f;
    pageAudioCtr.alpha = 0.0001f;
    if (rectview.helperIcon_popHide) {
        rectview.helperIcon.alpha = 1.f;
    }
    [UIView animateWithDuration:0.3f animations:^{
        self.alpha = 1.f;
        readPlayBtn.alpha = 1.f;
        pageAudioCtr.alpha = 1.f;
        if (rectview.helperIcon_popHide) {
            rectview.helperIcon.alpha = 0.001f;
        }
    } completion:^(BOOL finished) {
        rectview.helperIcon.alpha = 1.f;
        if (rectview.helperIcon_popHide) {
            rectview.helperIcon.hidden = YES;
        }
    }];
}

- (void)playUnshow
{
    if (_webView) {
        [_webView removeFromSuperview];
        _webView = nil;
        if (_xBtn) {
            [_xBtn removeFromSuperview];
        }
    }
    [self cleanAudio];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
    if (rectview.helperIcon.hidden == YES) {
        rectview.helperIcon.alpha = 0.001f;
    }
    rectview.helperIcon.hidden = NO;
    [UIView animateWithDuration:0.3f animations:^{
        self.alpha = 0.0001f;
        readPlayBtn.alpha = 0.0001f;
        pageAudioCtr.alpha = 0.0001f;
        if (rectview.helperIcon_popHide) {
            rectview.helperIcon.alpha = 1.f;
        }
    } completion:^(BOOL finished) {
        rectview.helperIcon.hidden = NO;
        rectview.helperIcon.alpha = 1.f;
        [self removeFromSuperview];
        [[ReadBookVOrH_VC currentReadInstance] dismissPopWindow];
        if (_webView) _webView = nil;
        if (_xBtn) _xBtn = nil;
    }];
    
}

- (void)playUnshow_must
{
    [self cleanAudio];
    rectview.helperIcon.hidden = NO;
    rectview.helperIcon.alpha = 1.f;
    [self removeFromSuperview];
}

- (void)_x
{
    [self playUnshow];
}

- (void)cleanAudio
{
    if (mp3File != nil) {
        NSString* mp3F = mp3File;
        mp3File = nil;
        [[TLSoundPlayer shareSingle] stopFilePlay_andClean:mp3F];
    }
    if (mp3File_unCode) {
        [[NSFileManager defaultManager] removeItemAtPath:mp3File_unCode error:nil];
    }
}

- (void)removeFromSuperview
{
    if(pageAudioCtr && pageAudioCtr.superview){
        [pageAudioCtr removeFromSuperview],pageAudioCtr = nil;
    }
    if(readPlayBtn && readPlayBtn.superview){
        [readPlayBtn removeFromSuperview],readPlayBtn = nil;
    }
    [self removeRectViewPop:rectview];
    [super removeFromSuperview];
}


- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSNumber* getRet = [self msgTo_menthed:@"pepGet_webView:shouldStartLoadWithRequest:" refs:@[webView,request] needReturnValue:YES];
    if (getRet != nil && getRet.boolValue) {
        return NO;
    }
    return YES;
}


- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGRect frame = webView.frame;
    CGRect frameTemp = frame;
    frame.size.height = 1;
    webView.frame = frame;
    frame.size.height = webView.scrollView.contentSize.height;
    //NSLog(@"frame = %@", [NSValue valueWithCGRect:frame]);
    webView.frame = frameTemp;
    webView.scrollView.contentSize = frame.size;
    //处理图片滚动示意标签
    [self addHostArea_adv_Img_Sign:webView.scrollView];
}

- (void)tlSoundActionToStop_PlayingFile:(NSString *)fileFullPath
{
    [self _x];
}

- (void)tlSoundPlayerDidFinishPlayingFile:(NSString *)fileFullPath
{
    [self _x];
}

@end
